package edu.tjpu.share.task;

import java.util.HashMap;
import java.util.List;

import org.phprpc.PHPRPC_Client;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.biz.ISelectGMC;
import edu.tjpu.share.newui.GetClasses;
import edu.tjpu.share.po.Classes;
import edu.tjpu.share.po.Server;

public class GetClassesTask extends
		AsyncTask<HashMap<String, Object>, Integer, HashMap<String, Object>> {

	@Override
	protected HashMap<String, Object> doInBackground(
			HashMap<String, Object>... maps) {

		List<Classes> classList = null;
		Handler handler = (Handler) maps[0].get(Fields.HANDLER);
		Server serverinfo = (Server) maps[0].get(Fields.SERVER_INFO);
		int mid = (Integer) maps[0].get(Fields.MID);

		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append("/ShareServer/servlet/SelectGMCServlet");
		
		try {
			PHPRPC_Client SelectGMCRPCClient = new PHPRPC_Client(
					sbhost.toString());
			ISelectGMC selectGMC = (ISelectGMC) SelectGMCRPCClient
					.useService(ISelectGMC.class);
			classList = selectGMC.getClassList(mid);
		} catch (Exception e) {
			Message msg = new Message();
			msg.what = Fields.NETWORK_CONNECTION_ERROR;
			handler.sendMessage(msg);
			return null;
		}

		HashMap<String, Object> outmap = new HashMap<String, Object>();
		outmap.put(Fields.CLASS_LIST, classList);
		outmap.put(Fields.HANDLER, handler);
		return outmap;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onPostExecute(HashMap<String, Object> result) {
		super.onPostExecute(result);
		if (isCancelled()) {
			result = null;
		}
		if (result != null) {
			List<Classes> classList = (List<Classes>) result
					.get(Fields.CLASS_LIST);
			Handler handler = (Handler) result.get(Fields.HANDLER);
			GetClasses.setClassList(classList);
			handler.sendEmptyMessage(0);
		}
	}

}
